package com.yuanfeng.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.base.entity.BaseInvoiceAddressEntity;
import com.yuanfeng.base.mapper.BaseInvoiceAddressMapper;
import com.yuanfeng.base.service.BaseDistrictService;
import com.yuanfeng.base.service.BaseInvoiceAddressService;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.TokenUtils;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 *
 */
@Service
public class BaseInvoiceAddressServiceImpl extends ServiceImpl<BaseInvoiceAddressMapper, BaseInvoiceAddressEntity>
    implements BaseInvoiceAddressService{

    @Autowired
    private BaseDistrictService districtService;

    @Override
    public ResponseResult queryAddressTmp(Map<String, Object> param) {
        String token = (String) param.get("token");
        ResponseResult tokenResult = TokenUtils.checkToken(token);
        if (tokenResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
            return tokenResult;
        } else {
            param.put("userId", tokenResult.getData().toString());
        }
        try {
            BaseInvoiceAddressEntity addressTmpEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<BaseInvoiceAddressEntity>()
                    .eq(BaseInvoiceAddressEntity::getUserId, param.get("userId").toString())
                    .eq(BaseInvoiceAddressEntity::getAddressId, param.get("addressId").toString()));
            String addressInfo = "";
            addressInfo = districtService.getAddressString(addressTmpEntity.getAddressProvince(), addressTmpEntity.getAddressCity(), addressTmpEntity.getAddressArea()).getData().toString();
            addressTmpEntity.setAddressInfo(addressInfo);
            return ResponseResult.success(addressTmpEntity);
        } catch (Exception e) {

            log.error(e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult updateAddressTmp(Map<String, Object> param) {
        String token = (String) param.get("token");
        ResponseResult tokenResult = TokenUtils.checkToken(token);
        if (tokenResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
            return tokenResult;
        } else {
            param.put("userId", tokenResult.getData().toString());
        }
        try {
            //是否默认收票人地址
            int isDefault = Integer.parseInt(param.get("isDefault").toString());
            //如果新插入的为默认配置，则将其他的配置isDefault置为0
            if (1 == isDefault) {
                this.baseMapper.update(null, new LambdaUpdateWrapper<BaseInvoiceAddressEntity>()
                        .eq(BaseInvoiceAddressEntity::getUserId, param.get("userId").toString())
                        .set(BaseInvoiceAddressEntity::getIsDefault, 0));
            }
            this.baseMapper.updateAddressTmp(param);
            return ResponseResult.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail();
        }
    }

    @Override
    public ResponseResult deleteAddressTmp(Map<String, Object> param) {
        String token = (String) param.get("token");
        ResponseResult tokenResult = TokenUtils.checkToken(token);
        if (tokenResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
            return tokenResult;
        } else {
            param.put("userId", tokenResult.getData().toString());
        }
        try {
            this.baseMapper.delete(new LambdaQueryWrapper<BaseInvoiceAddressEntity>()
                    .eq(BaseInvoiceAddressEntity::getUserId, param.get("userId").toString())
                    .eq(BaseInvoiceAddressEntity::getAddressId, param.get("addressId").toString()));
            return ResponseResult.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult queryInvoiceAddressList(Map<String, Object> param) {
        String token = (String) param.get("token");
        ResponseResult tokenResult = TokenUtils.checkToken(token);
        if (tokenResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
            return tokenResult;
        } else {
            param.put("userId", tokenResult.getData().toString());
        }
        try {
            IPage<BaseInvoiceAddressEntity> page = this.baseMapper.selectPage(new Query<BaseInvoiceAddressEntity>().getPage(param),
                    new LambdaQueryWrapper<BaseInvoiceAddressEntity>().eq(BaseInvoiceAddressEntity::getUserId, param.get("userId").toString())
                            .orderByDesc(BaseInvoiceAddressEntity::getCreateTime));
            for (BaseInvoiceAddressEntity tmp : page.getRecords()) {

                String completeAddress = districtService.getAddressString(tmp.getAddressProvince(), tmp.getAddressCity(), tmp.getAddressArea()).getData().toString();
                tmp.setPreCompleteAddress(completeAddress);
                completeAddress = completeAddress + tmp.getAddressDetail();
                tmp.setCompleteAddress(completeAddress);
            }

            return ResponseResult.success(PageUtils.getPage(page));
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult insertAddressTmp(Map<String, Object> param) {
        String token = (String) param.get("token");
        ResponseResult tokenResult = TokenUtils.checkToken(token);
        if (tokenResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
            return tokenResult;
        } else {
            param.put("userId", tokenResult.getData().toString());
        }
        try {
            if (param.get("addressId") == null || param.get("addressId") == "") {
                Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<BaseInvoiceAddressEntity>()
                        .eq(BaseInvoiceAddressEntity::getUserId, param.get("userId").toString()));
                //发票模版大于10个无法添加
                if (null != count && count >= 10) {
                    return ResponseResult.success(BizCodeEnume.INVOICE_ADDRESS_TEMPLATES_HAS_REACHED_THE_UPPER_LIMIT.getMsg());
                }
                //是否默认收票人地址
                int isDefault = Integer.parseInt(param.get("isDefault").toString());
                //如果新插入的为默认配置，则将其他的配置isDefault置为0
                if (1 == isDefault) {
                    this.baseMapper.update(null, new LambdaUpdateWrapper<BaseInvoiceAddressEntity>()
                            .eq(BaseInvoiceAddressEntity::getUserId, param.get("userId").toString())
                            .set(BaseInvoiceAddressEntity::getIsDefault, 0));
                }
                this.baseMapper.insertAddressTmp(param);
            } else {
                this.baseMapper.updateAddressTmp(param);
            }
            return ResponseResult.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
    }
}




